import { ProForm, ProFormSelect, ProFormText } from '@ant-design/pro-components';
import { Form, Modal, TreeSelect, message } from 'antd';
import { FormInstance } from 'antd/lib/form/Form';
import { useRef, useState } from 'react';
import { TenantChangeBelongBean, TenantItem } from '../data';
import { queryDepartment } from '@/pages/user/Department/service';
import { queryAdminListByPosition, queryPositionByDep } from '@/pages/user/Admin/service';

interface UpdateTenantBelongProps {
    tenant: TenantItem;
    onSubmit: (values: TenantChangeBelongBean) => Promise<void>;
    onCancel: (flag?: boolean) => void;
    modalVisible: boolean;
    visibleHandler: (flag?: boolean) => void;
}

export default (props: UpdateTenantBelongProps) => {
    const {
        onSubmit: handleUpdate,
        onCancel: handleUpdateModalVisible,
        modalVisible: updateModalVisible,
        tenant
    } = props;
    const formRef = useRef<FormInstance>();

    const [treeDate, setTreeDate] = useState<any[]>([]);
    const [positionData, setPositionData] = useState<any[]>();
    const [owningAccount, setOwningAccount] = useState<any[]>([{ value: tenant.belong, label: tenant.belong_name }]);
    const [oneTreeDisplay, setOneTreeDisplay] = useState(false);
    const [twoTreeDisplay, setTwoTreeDisplay] = useState(true);
    const [selectDisplay, setSelectDisplay] = useState(true);
    const [departmentHidden, setDepartmentHidden] = useState(true);
    const [positionHidden, setPositionHidden] = useState(true);

    function convertData(data: { id: any; name: any; next_level: string | any[] }) {
        const node = {
            value: data.id,
            title: data.name,
            children: [] as any,
        };
        if (data.next_level && data.next_level.length > 0) {
            for (let i = 0; i < data.next_level.length; i++) {
                const child = convertData(data.next_level[i]);
                node.children.push(child);
            }
        }
        return node;
    }

    const resetData = async () => {
        queryDepartment().then((res) => {
            if (res && res.code == 0) {
                const data = res?.data;
                const convert = [];
                if (data && data.length > 0) {
                    for (let i = 0; i < data.length; i++) {
                        convert.push(convertData(data[i]));
                    }
                    setTreeDate(convert);
                }
            }
        });
    }

    return (
        <Modal
            title="修改客户所属权"
            open={updateModalVisible}
            width={550}
            footer={null}
            centered
            onCancel={() => handleUpdateModalVisible(false)}
            afterClose={() => handleUpdateModalVisible(false)}
        >
            <ProForm<TenantChangeBelongBean>
                onFinish={(values) => handleUpdate(values)}
                onReset={() => {
                    resetData()
                    formRef.current?.setFieldValue('department_id', undefined)
                    formRef.current?.setFieldValue('position_id', undefined)
                    formRef.current?.setFieldValue('belong', undefined)
                    setOneTreeDisplay(false);
                    setTwoTreeDisplay(true);
                    setSelectDisplay(true);
                    setDepartmentHidden(false);
                    setPositionHidden(false);
                }}
                formRef={formRef}
                layout="vertical"
            >

                <ProFormText
                    width={'xl'}
                    name="id"
                    label="id"
                    initialValue={tenant.id}
                    hidden={true}
                />
                <Form.Item
                    name="department_id"
                    label="部门选择"
                    hidden={departmentHidden}
                >
                    <TreeSelect
                        disabled={oneTreeDisplay}
                        showSearch
                        style={{ width: '100%' }}
                        dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                        placeholder="请选择部门"
                        allowClear
                        autoClearSearchValue
                        treeDefaultExpandAll
                        onChange={(newValue, _labelList) => {
                            if (newValue) {
                                queryPositionByDep(newValue).then((res) => {
                                    if (res && res.code == 0 && res.data.length > 0) {
                                        const data = res?.data;
                                        const convert = [];
                                        if (data && data.length > 0) {
                                            for (let i = 0; i < data.length; i++) {
                                                convert.push(convertData(data[i]));
                                            }
                                            setPositionData(convert);
                                            setOneTreeDisplay(true);
                                            setTwoTreeDisplay(false);
                                        }
                                    }else {
                                        message.error("暂无可选职位")
                                    }
                                });
                            }
                        }}
                        treeData={treeDate}
                    />
                </Form.Item>
                <Form.Item
                    name="position_id"
                    label="职位选择"
                    hidden={positionHidden}
                >
                    <TreeSelect
                        disabled={twoTreeDisplay}
                        autoClearSearchValue
                        showSearch
                        onChange={(newValue) => {
                            queryAdminListByPosition(newValue).then((res) => {
                                if (res && res.code == 0 && res.data.length > 0) {
                                    setOwningAccount(
                                        res.data?.map((item: { id: any; name: any }) => {
                                            return {
                                                value: item.id,
                                                label: item.name,
                                            };
                                        }),
                                    );
                                    setTwoTreeDisplay(true);
                                    setSelectDisplay(false);
                                } else {
                                    message.error('该职位暂无管理员');
                                }
                            });
                        }}
                        style={{ width: '100%' }}
                        dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                        placeholder="请选择职位"
                        allowClear
                        treeDefaultExpandAll
                        treeData={positionData}
                    />
                </Form.Item>
                <ProFormSelect
                    initialValue={tenant.belong}
                    options={owningAccount}
                    label={'所属管理员'}
                    disabled={selectDisplay}
                    name="belong"
                    placeholder="选择所属管理员（请先选择职位）"
                />


            </ProForm>
        </Modal>
    );
};
